//
//  OilVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/14.
//

import UIKit
import WebKit

class PowerVC: ZMViewController {
    
    @IBOutlet weak var topBg: UIView!
    @IBOutlet weak var addBtn: UIButton!
    @IBOutlet weak var historyList: UITableView!
    @IBOutlet weak var historyHeight: NSLayoutConstraint!
    @IBOutlet weak var detailInfoView: UIView!
    @IBOutlet weak var detailInfoHeight: NSLayoutConstraint!
    
    lazy var wkWeb: WKWebView = {
        let userContentController = WKUserContentController()
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = userContentController
        wkWebConfig.allowsInlineMediaPlayback = true
        let web = WKWebView(frame: CGRect.zero, configuration: wkWebConfig)
        web.scrollView.showsVerticalScrollIndicator = false
        web.backgroundColor = .white
        web.navigationDelegate = self
        web.scrollView.bounces = false
        detailInfoView.addSubview(web)
        web.snp.makeConstraints { (make) in
            make.top.equalTo(54)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.bottom.equalTo(-16)
        }
        return web
    }()
    
    var history = [[String: String]]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestWeb()
        setUI()
        setTable()
        bindAction()
        getHistory()
    }
    
    func setUI() {
        title = "电费缴费"
        view.backgroundColor = "#F5F5F5".zm.hex()
        emptyImg = "nodata"
        emptyTitle = "暂无缴费"
        addNodataScrollView(scrollView: historyList)
        setRightCustomBtn(titleStr: "缴费记录", color: "#333333".zm.hex(), font: UIFont.zm.fontRegular(size: 14)) { [unowned self] sender in
            self.navigationController?.pushViewController(PowerHistoryVC(), animated: true)
        }
    }
    
    func setTable() {
        historyList.register(UINib(nibName: "PowerHistoryCell", bundle: nil), forCellReuseIdentifier: "PowerHistoryCell")
        historyList.rowHeight = 76
        historyList.delegate = self
        historyList.dataSource = self
        historyList.separatorStyle = .none
        let view = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_W, height: 12))
        historyList.tableFooterView = view
    }
    
    func getHistory(_ number: String = "", _ city: [String] = []) {
        if number == "" {
            if let data = UserDefaults.standard.object(forKey: "powerHistory") as? [[String: String]] {
                history = data
                historyList.reloadData()
            }
        } else {
            if history.filter({return $0["number"] == number}).count == 0 {
                history.insert(["number":number,"province":city[0],"city":city[1]], at: 0)
                if history.count == 6 {
                    history.removeLast()
                }
            } else {
                var index = 0
                for i in 0..<history.count {
                    if history[i]["number"] == number {
                        index = i
                        break
                    }
                }
                history[index] = ["number":number,"province":city[0],"city":city[1]]
            }
            historyList.reloadData()
            UserDefaults.standard.set(history, forKey: "powerHistory")
            UserDefaults.standard.synchronize()
        }
    }
    
    // MARK: - bindAction
    func bindAction() {
        historyList.rx.observeWeakly(CGSize.self, "contentSize").subscribe(onNext: { [unowned self] (change) in
            self.historyHeight.constant = change!.height == 12 ? 300 : change!.height
        }).disposed(by: disposeBag)
        
        addBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            let vc = PowerAddVC()
            self.navigationController?.pushViewController(vc, animated: true)
            vc.saveHistory = { [unowned self] (val, city) in
                self.getHistory(val, city)
            }
        }).disposed(by: disposeBag)
        
        wkWeb.scrollView.rx.observeWeakly(CGSize.self, "contentSize").subscribe(onNext: { [unowned self] (change) in
            self.detailInfoHeight.constant = change!.height + 70
        }).disposed(by: disposeBag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        topBg.layoutIfNeeded()
        topBg.style.GradientLeftToRight(Top: "#2C7EDF".zm.hex(), Bottom: UIColor.zm.color(hexString: "#2C7EDF", 0))
    }
}

extension PowerVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return history.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PowerHistoryCell", for: indexPath) as! PowerHistoryCell
        cell.number.text = history[indexPath.row]["number"]!
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = PowerAddVC()
        let info = history[indexPath.row]
        vc.numberStr = info["number"]!
        vc.cityArr = [info["province"]!, info["city"]!]
        navigationController?.pushViewController(vc, animated: true)
        vc.saveHistory = { [unowned self] (val, city) in
            self.getHistory(val, city)
        }
    }
}

extension PowerVC: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
            let imgSize = """
            var imgs = document.getElementsByTagName("img")
            for (var i = 0; i < imgs.length; i++) {
                imgs[i].setAttribute('width', '99%')
            }
            """
            webView.evaluateJavaScript(imgSize, completionHandler: nil)
            
            webView.evaluateJavaScript("""
                      var oMeta = document.createElement('meta');
                      oMeta.content = 'width=device-width, initial-scale=1.0, user-scalable=0';
                      oMeta.name = 'viewport';
                      document.getElementsByTagName('head')[0].appendChild(oMeta);
                      """) { flag, error in }
            
        }
        
    }
}

// MARK: - Request Action
extension PowerVC {
    func requestWeb() {
        CommonAPI.getDetail(ArticleType.powerIntro.rawValue).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            let json = JSON(resp)
            self.wkWeb.loadHTMLString(json["content"].stringValue.zm.htmlBigSizeString(), baseURL: nil)
        }).disposed(by: disposeBag)
    }
}
